package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("CrawlerdetectstatusRestController")
public class CrawlerdetectstatusRestController extends CmiEmaController {

	/**
	 * Create a new Crawlerdetectstatus entity
	 * 
	 */
	@RequestMapping(value = "/newCrawlerdetectstatus", method = RequestMethod.POST)
	@ResponseBody
	public Object newCrawlerdetectstatus(@RequestBody Crawlerdetectstatus crawlerdetectstatus) {
		crawlerdetectstatusService.saveCrawlerdetectstatus(crawlerdetectstatus);
		return JSONObject.parse(cmiPsonService
				.toJsonString(crawlerdetectstatusDAO.findCrawlerdetectstatusByPrimaryKey(crawlerdetectstatus.getId()), 2));
	}

	@RequestMapping(value = "/restNewCrawlerdetectstatus", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewCrawlerdetectstatus(@RequestBody String crawlerdetectstatusJson) {
		Crawlerdetectstatus crawlerdetectstatus = new Gson().fromJson(crawlerdetectstatusJson,
				Crawlerdetectstatus.class);
		appendReferences(crawlerdetectstatus);
		crawlerdetectstatusService.saveCrawlerdetectstatus(crawlerdetectstatus);
		return JSONObject.parse(cmiPsonService
				.toJsonString(crawlerdetectstatusDAO.findCrawlerdetectstatusByPrimaryKey(crawlerdetectstatus.getId()), 2));
	}

	@RequestMapping(value = "/saveCrawlerdetectstatus", method = RequestMethod.PUT)
	@ResponseBody
	public Crawlerdetectstatus saveCrawlerdetectstatus(@RequestBody Crawlerdetectstatus crawlerdetectstatus) {
		crawlerdetectstatusService.saveCrawlerdetectstatus(crawlerdetectstatus);
		return crawlerdetectstatusDAO.findCrawlerdetectstatusByPrimaryKey(crawlerdetectstatus.getId());
	}

	@RequestMapping(value = "/restSaveCrawlerdetectstatus", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveCrawlerdetectstatus(@RequestBody String crawlerdetectstatusJson) {
		Crawlerdetectstatus crawlerdetectstatus = new Gson().fromJson(crawlerdetectstatusJson,
				Crawlerdetectstatus.class);
		appendReferences(crawlerdetectstatus);
		CmiPsonService cmiPsonService = new CmiPsonService();
		crawlerdetectstatusService.saveCrawlerdetectstatus(crawlerdetectstatus);
		return JSONObject.parse(cmiPsonService
				.toJsonString(crawlerdetectstatusDAO.findCrawlerdetectstatusByPrimaryKey(crawlerdetectstatus.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteCrawlerdetectstatus/{crawlerdetectstatusId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteCrawlerdetectstatus(@PathVariable Integer crawlerdetectstatusId) {
		Crawlerdetectstatus crawlerdetectstatus = crawlerdetectstatusDAO
				.findCrawlerdetectstatusByPrimaryKey(crawlerdetectstatusId);
		crawlerdetectstatusService.deleteCrawlerdetectstatus(crawlerdetectstatus);
	}

	@RequestMapping(value = "/restConfirmDeleteCrawlerdetectstatuss")
	@ResponseBody
	public Object restConfirmDeleteCrawlerdetectstatuss(@RequestBody Set<Integer> deleteCrawlerdetectstatussIds) {
		Set<Crawlerdetectstatus> deleteCrawlerdetectstatuss = crawlerdetectstatusDAO
				.findCrawlerdetectstatussByIds(deleteCrawlerdetectstatussIds);
		Set<Crawlerdetectstatus> referencedCrawlerdetectstatuss = crawlerdetectstatusService
				.loadReferenceCrawlerdetectstatuss(deleteCrawlerdetectstatuss);
		deleteCrawlerdetectstatuss.removeAll(referencedCrawlerdetectstatuss);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedCrawlerdetectstatuss);
		jsonObject.put("deleteEntitys", deleteCrawlerdetectstatuss);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteCrawlerdetectstatuss")
	@ResponseBody
	public Object restDeleteCrawlerdetectstatuss(@RequestBody Set<Crawlerdetectstatus> deleteCrawlerdetectstatuss) {
		Iterator<Crawlerdetectstatus> iterator = deleteCrawlerdetectstatuss.iterator();
		while (iterator.hasNext()) {
			Crawlerdetectstatus currentCrawlerdetectstatus = iterator.next();
			crawlerdetectstatusService.deleteCrawlerdetectstatus(currentCrawlerdetectstatus);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listCrawlerdetectstatuss");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadCrawlerdetectstatus/{crawlerdetectstatusId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerdetectstatus(@PathVariable Integer crawlerdetectstatusId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				crawlerdetectstatusDAO.findCrawlerdetectstatusByPrimaryKey(crawlerdetectstatusId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadCrawlerdetectstatusCrawlerdetects/{crawlerdetectstatusId}/crawlerdetects/{relatedcrawlerdetectId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerdetectstatusCrawlerdetects(@PathVariable Integer crawlerdetectstatusId,
			@PathVariable Integer relatedcrawlerdetectId, @RequestBody CmiPagination cmiPagination) {
		Crawlerdetect crawlerdetect = crawlerdetectDAO.findCrawlerdetectByPrimaryKey(relatedcrawlerdetectId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(crawlerdetect, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadCrawlerdetectstatusCrawlerevents/{crawlerdetectstatusId}/crawlerevents/{relatedcrawlereventId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerdetectstatusCrawlerevents(@PathVariable Integer crawlerdetectstatusId,
			@PathVariable Integer relatedcrawlereventId, @RequestBody CmiPagination cmiPagination) {
		Crawlerevent crawlerevent = crawlereventDAO.findCrawlereventByPrimaryKey(relatedcrawlereventId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(crawlerevent, 2, cmiPagination));
	}

	public void appendReferences(Crawlerdetectstatus crawlerdetectstatus) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Crawlerdetect> crawlerdetectsForCrawlerdetectstatus = new HashSet<>();
		for (Crawlerdetect crawlerdetect_Crawlerdetectstatus : crawlerdetectstatus
				.getCrawlerdetectsForCrawlerdetectstatus()) {
			crawlerdetectsForCrawlerdetectstatus
					.add(crawlerdetectService.findCrawlerdetectByPrimaryKey(crawlerdetect_Crawlerdetectstatus.getId()));
		}
		crawlerdetectstatus.setCrawlerdetectsForCrawlerdetectstatus(crawlerdetectsForCrawlerdetectstatus);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Crawlerevent> crawlereventsForCrawlerdetectstatus = new HashSet<>();
		for (Crawlerevent crawlerevent_Crawlerdetectstatus : crawlerdetectstatus
				.getCrawlereventsForCrawlerdetectstatus()) {
			crawlereventsForCrawlerdetectstatus
					.add(crawlereventService.findCrawlereventByPrimaryKey(crawlerevent_Crawlerdetectstatus.getId()));
		}
		crawlerdetectstatus.setCrawlereventsForCrawlerdetectstatus(crawlereventsForCrawlerdetectstatus);
	}

	@RequestMapping(value = "/restGetCrawlerdetectstatusCrawlerdetects/{crawlerdetectstatusId}/crawlerdetects", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetCrawlerdetectstatusCrawlerdetects(@PathVariable Integer crawlerdetectstatusId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(crawlerdetectstatusDAO.findCrawlerdetectstatusByPrimaryKey(crawlerdetectstatusId)
						.getCrawlerdetectsForCrawlerdetectstatus(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetCrawlerdetectstatusCrawlerevents/{crawlerdetectstatusId}/crawlerevents", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetCrawlerdetectstatusCrawlerevents(@PathVariable Integer crawlerdetectstatusId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(crawlerdetectstatusDAO.findCrawlerdetectstatusByPrimaryKey(crawlerdetectstatusId)
						.getCrawlereventsForCrawlerdetectstatus(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListCrawlerdetectstatuss", method = RequestMethod.GET)
	@ResponseBody
	public Object restListCrawlerdetectstatuss() {
		return JSONObject.parse(cmiPsonService.toJsonString(crawlerdetectstatusService.loadCrawlerdetectstatuss(), 2));
	}

	@RequestMapping(value = "/restListCrawlerdetectstatussPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListCrawlerdetectstatussPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = crawlerdetectstatusPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Crawlerdetectstatus> crawlerdetectstatuss = crawlerdetectstatusDAO.findAllCrawlerdetectstatuss(startResult,
				cmiPagination.getPaginationSize());
		String crawlerdetectstatusString = cmiPsonService.toPsonString(crawlerdetectstatuss, 2, cmiPagination);

		return JSONObject.parse(crawlerdetectstatusString);
	}

	@RequestMapping("/crawlerdetectstatusSelectBox")
	@ResponseBody
	public JSONObject crawlerdetectstatusSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Crawlerdetect":
				entitySet = crawlerdetectService.loadCrawlerdetectsByIdSet(searchValue);
				break;
			case "Crawlerevent":
				entitySet = crawlereventService.loadCrawlereventsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Crawlerdetect":
				entitySet = crawlerdetectDAO.findAllCrawlerdetects((pageNumber - 1) * paginationSize, paginationSize);
				count = crawlerdetectService.countCrawlerdetects();
				break;
			case "Crawlerevent":
				entitySet = crawlereventDAO.findAllCrawlerevents((pageNumber - 1) * paginationSize, paginationSize);
				count = crawlereventService.countCrawlerevents();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Crawlerdetect":
				entitySet = crawlerdetectDAO.findCrawlerdetectByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = crawlerdetectService.countCrawlerdetectsByName(queryword);
				break;
			case "Crawlerevent":
				entitySet = crawlereventDAO.findCrawlereventByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = crawlereventService.countCrawlereventsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
